package fr.insee.rome.string.norm;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;


public class MapSynonymes implements Synonymes {

	private static Synonymes instance = null;
	private Map<Pattern, String> synonymes;
	
	private MapSynonymes(){
		this.synonymes = new HashMap<Pattern, String>();
		try {
			this.load("./txt/genres.csv");
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static Synonymes getInstance(){
		if(instance == null){
			instance = new MapSynonymes();
		}
		return instance;
	}

	public String get(Pattern key) {

		String value = synonymes.get(key);
		return value;
	}

	public void put(String key, String value) {
		
		synonymes.put(
			Pattern.compile("(^" + key + " )|( " + key + " )|( " + key + "$)"),
			value
		);
	}

	public Iterator<Pattern> iterator() {
		return synonymes.keySet().iterator();
	}
	
	private void load(String path) throws IOException {
		
		InputStream stream = new FileInputStream(path);
		Reader reader = new InputStreamReader(stream);
		BufferedReader buffer = new BufferedReader(reader);

		String line = null;
		String[] tokens = null;
		while ((line = buffer.readLine()) != null) {
			tokens = line.split("=");
			this.put(tokens[1], tokens[0]);
		}
		
		buffer.close();
		reader.close();
		stream.close();
	}
}
